package com.work.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.work.service.IStudentService;
import com.work.service.impl.StudentServiceImpl;
import com.work.vo.ExcelVo;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

// 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
@Slf4j
public class ExcelListener extends AnalysisEventListener<ExcelVo> {

    private static final int BATCH_COUNT = 100;
    private List<ExcelVo> list = new ArrayList<>();

    private IStudentService studentService;

    public ExcelListener(){
        studentService = new StudentServiceImpl();
    }

    public ExcelListener(IStudentService studentService){
        this.studentService = studentService;
    }

    //读取数据的时候会执行invoke方法
    @Override
    public void invoke(ExcelVo excelVo, AnalysisContext analysisContext) {
        list.add(excelVo);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if(list.size() >= BATCH_COUNT){
            this.studentService.saveList(list);
            list.clear();           //清空list
        }
    }

    //所有的数据解析完成之后都会来调用
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        this.studentService.saveList(list); //确保最后遗留的数据保存在数据库中
    }

}
